<template>
  <div class="app-container">
    <!-- ====== Tab栏：待处理 / 已处理 ====== -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="待处理" name="unhandled"></el-tab-pane>
      <el-tab-pane label="已处理" name="handled"></el-tab-pane>
    </el-tabs>

    <!-- ====== 搜索表单 ====== -->
    <el-form :model="queryParams" :inline="true" label-width="120px" class="search-form">
      <el-form-item label="单据编号">
        <el-input v-model="queryParams.code" placeholder="请输入单据编号" clearable style="width: 220px" />
      </el-form-item>

      <el-form-item label="申请人">
        <el-input v-model="queryParams.applicat" placeholder="请输入申请人" clearable style="width: 220px" />
      </el-form-item>

      <el-form-item label="单据类型">
        <el-select v-model="queryParams.type" placeholder="请选择单据类型" clearable style="width: 180px">
          <el-option label="请假" :value="1" />
          <el-option label="退住" :value="2" />
          <el-option label="入住" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="流程状态">
        <el-select v-model="queryParams.status" placeholder="请选择流程状态" clearable style="width: 180px">
          <el-option label="申请中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="已关闭" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="申请时间">
        <el-date-picker
          v-model="daterangeApplyTime"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          range-separator="-"
          style="width: 320px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- ====== 表格 ====== -->
    <el-table v-loading="loading" :data="taskList" stripe style="margin-top: 20px">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="单据编号" prop="code" align="center" />
      <el-table-column label="单据标题" align="center">
        <template #default="scope">
          {{ scope.row.title || ((scope.row.applicat || '未知申请人') + '的' + formatType(scope.row.type) + '申请') }}
        </template>
      </el-table-column>
      <el-table-column label="单据类型" align="center">
        <template #default="scope">{{ formatType(scope.row.type) }}</template>
      </el-table-column>
      <el-table-column label="申请人" prop="applicat" align="center" />
      <el-table-column label="申请时间" align="center">
        <template #default="scope">{{ formatTime(scope.row.applicationTime) }}</template>
      </el-table-column>
      <el-table-column label="完成时间" align="center">
        <template #default="scope">{{ scope.row.finishTime ? formatTime(scope.row.finishTime) : '——' }}</template>
      </el-table-column>
      <el-table-column label="等待时长" align="center">
        <template #default="scope">{{ calculateWaitTime(scope.row.applicationTime) }}</template>
      </el-table-column>
      <el-table-column label="流程状态" align="center">
        <template #default="scope">
          <el-tag :type="formatStatusTagType(scope.row.status)" effect="plain">{{ formatStatus(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button type="primary" link @click="handleOperate(scope.row)">处理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- ====== 分页 ====== -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-size="queryParams.pageSize"
      :current-page="queryParams.pageNum"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { postPendingTasks } from '@/api/tasking/tasking'
import { useRouter } from 'vue-router'

const router = useRouter()

// ===================== 常量映射 =====================
const TYPE_MAP = { 1: '请假', 2: '退住', 3: '入住' }
const STATUS_MAP = { 1: '申请中', 2: '已完成', 3: '已关闭' }
const STATUS_TAG_MAP = { 1: 'warning', 2: 'success', 3: 'danger' }
// const reqType = 1
// ===================== 响应式数据 =====================
const activeTab = ref('unhandled') // 默认“待处理”
const daterangeApplyTime = ref([])
const taskList = ref([])
const total = ref(0)
const loading = ref(false)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  code: null,
  applicat: null,
  type: null,
  status: null,
  reqType:0,
  isHandle: 0 // 0=待处理, 1=已处理
})

// ===================== 获取列表 =====================
const getList = () => {
  loading.value = true
  const params = { ...queryParams }
  if (daterangeApplyTime.value.length === 2) {
    params.startTime = daterangeApplyTime.value[0]
    params.endTime = daterangeApplyTime.value[1]
  }
  postPendingTasks(params)
    .then(res => {
      taskList.value = res.data || []
      total.value = res.total || taskList.value.length
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

// ===================== Tab切换 =====================
const handleTabChange = (tabName) => {
  queryParams.isHandle = tabName === 'handled' ? 1 : 0
  handleQuery()
}

// ===================== 搜索与重置 =====================
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryParams.code = null
  queryParams.applicat = null
  queryParams.type = null
  queryParams.status = null
  daterangeApplyTime.value = []
  handleQuery()
}

// ===================== 分页 =====================
const handlePageChange = page => {
  queryParams.pageNum = page
  getList()
}
const handleSizeChange = size => {
  queryParams.pageSize = size
  queryParams.pageNum = 1
  getList()
}

// ===================== 操作按钮（处理） =====================
const handleOperate = row => {
  const taskName = row.taskName || ''
  const { id, processInstanceId } = row

  // 跳转时带上任务ID与流程实例ID
  const query = {
    taskId: id,
    taskName: taskName,
    processInstanceId: processInstanceId
  }

  // 根据任务名称判断跳转目标
  if (taskName.includes('入住评估')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckInApply', query })
  } else if (taskName.includes('副院长审批')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckInApply', query })
  } else if (taskName.includes('入住选配-处理')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckInApply', query })
  } else if (taskName.includes('签约办理-处理')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckInApply', query })
  } else if (taskName.includes('退住审核')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })
  } else if (taskName.includes('退住解除')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })
  } else if (taskName.includes('退住调整')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })}
    else if (taskName.includes('退住调整')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })}
    else if (taskName.includes('账单结算')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })}
    else if (taskName.includes('退住账单')) {
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })}
    else if (taskName.includes('护理组主管')) {
    router.push({ name: 'LeaveApproval', query })}
    else if (taskName.includes('护理部部长')) {
    router.push({ name: 'LeaveApproval', query })}
    else if (taskName.includes('院长-退住')) {
      router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })}
  else {
    // 默认兜底
    router.push({ path: '/CollaborationWork/MyApply/CheckoutApply', query })
  }
}

// ===================== 工具函数 =====================
const formatType = type => TYPE_MAP[type] || '未知'
const formatStatus = status => STATUS_MAP[status] || '未知'
const formatStatusTagType = status => STATUS_TAG_MAP[status] || 'info'
const formatTime = time => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')} ${String(date.getHours()).padStart(2,'0')}:${String(date.getMinutes()).padStart(2,'0')}:${String(date.getSeconds()).padStart(2,'0')}`
}
const calculateWaitTime = applyTime => {
  if (!applyTime) return '——'
  const diff = new Date() - new Date(applyTime)
  const days = Math.floor(diff / (1000*60*60*24))
  const hours = Math.floor((diff % (1000*60*60*24)) / (1000*60*60))
  const minutes = Math.floor((diff % (1000*60*60)) / (1000*60))
  let result = ''
  if (days > 0) result += `${days}天`
  if (hours > 0) result += `${hours}小时`
  if (minutes > 0) result += `${minutes}分钟`
  return result || '0秒'
}

// ===================== 初始化加载 =====================
getList()
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
